package com.tjtt.tdm.system.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.tjtt.common.utils.StringUtil;
import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.base.PagingBean;
import com.tjtt.tdm.base.ParamBean;
import com.tjtt.tdm.exception.ServiceException;
import com.tjtt.tdm.system.bean.Organization;
import com.tjtt.tdm.system.service.LogService;
import com.tjtt.tdm.system.service.OrganizationService;
import com.tjtt.tdm.system.service.UserService;

public class OrganizationAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private OrganizationService organizationService;
	private LogService logService;
	private Organization organization;
	private String orgId;
	private String orgName;
	private int orgParentId;
	private UserService userService;

	private String page;
	private String rows;
	private String sidx;
	private String sord;
	private Long id;
	
	/** 查询所有的组织结构的方法 */
	public String searchAllOrgExec() throws IOException, ServiceException {
		setContentType();
		PrintWriter out = getResponse().getWriter();
		List<Organization> orgList = organizationService.getAllTypes();
		String result = getOrgJson(orgList);
		out.print(result);
		System.out.println(result);
		return null;
	}
	
	public String searchAllOrgBuFenExec() throws IOException, ServiceException {
		setContentType();
		PrintWriter out = getResponse().getWriter();
		List<Organization> orgList = organizationService.getAllTypesBuFen();
		String result = getOrgJson(orgList);
		out.print(result);
		System.out.println(result);
		return null;
	}
	/** 查询所有的组织结构的方法 */
	public String searchAllOrg4Exec() throws IOException, ServiceException {
		setContentType();
		PrintWriter out = getResponse().getWriter();
		List<Organization> orgList = organizationService.getAllTypes4();
		String result = getOrgJson(orgList);
		out.print(result);
		System.out.println(result);
		return null;
	}
	/**
	 * 生成json格式数据
	 * 
	 * @param orgs
	 * @return
	 */
	private String getOrgJson(List<Organization> orgs) {
		StringBuilder JSONStr = new StringBuilder();
		JSONStr.append("[");
		for (Organization org : orgs) {
			Long childrenNum = org.getChildrennum()==null?0l:org.getChildrennum();
			String icon = childrenNum > 0 ? "folder" : "file";
			String parentid = org.getOrgParentId() == null ? "" : org.getOrgParentId().toString();
			JSONStr.append("{\"text\":\"" + org.getOrgName() + "\",\"id\":\"" + org.getOrgId() + "\",\"name\":\"" + org.getOrgName() + "\",\"pId\":\"" + parentid + "\",\"des\":\""
					+ org.getOrgDesc() + "\",\"childrennum\":\"" + org.getChildrennum() + "\",\"leaf\":" + (childrenNum == 0) + ",\"cls\":\"" + icon + "\"},");
		}
		int hasN = JSONStr.lastIndexOf(",");
		if (hasN > 0) {
			JSONStr.deleteCharAt(JSONStr.lastIndexOf(","));
		}
		JSONStr.append("]");
		return JSONStr.toString();
	}

	/** 分页查询组织结构的方法 */
	public String findOraByPageExec() throws IOException, ServiceException {
		setContentType();
		
		 
		return null;
	}
	
	/**
	 * 组织机构树的展示
	 * @return
	 * @throws ServiceException List
	 * @author 张海娜
	 * @date 2012-9-24 上午10:03:44
	 */
	public List getOrganizationTree() throws ServiceException{
		List<Organization> findOrganizationByOrgParentId = organizationService.getAllTypes();
		return findOrganizationByOrgParentId;
		
	}
	
	/**
	 * 楼层管理树结构
	 * @return
	 * @throws ServiceException List
	 * @author 张海娜 quoted by zf
	 * @date 2013-3-14 上午10:03:44
	 */
	public String getOrganizationBFRTree() throws ServiceException{
		List findOrgB = organizationService.getAllTypesB();
		List findOrgF = organizationService.getAllTypesF();
		List findOrgR = organizationService.getAllTypesR();
		String[] viewArray={"id","name","pId","type"};
		Iterator it = findOrgB.iterator();
		Iterator it2 = findOrgF.iterator();
		Iterator it3 = findOrgR.iterator();
		JSONObject jso=null;
		JSONObject jso2=null;
		JSONObject jso3=null;
		String treeNode="";
		String treeNode2="";
		String treeNode3="";
		while (it.hasNext()) { 
			Object[] objlist = (Object[]) it.next();
			jso=getColumnValue(objlist,viewArray);
			if(jso!=null){
				
				if(treeNode!=""){
					treeNode+=jso+",";
				}else{
					treeNode=""+jso+",";
				}
			}else{
				treeNode="";
			}
			
		} 
		while (it2.hasNext()) { 
			Object[] objlist = (Object[]) it2.next();
			jso2=getColumnValue(objlist,viewArray);
			if(jso2!=null){
				
				if(treeNode2!=""){
					treeNode2+=jso2+",";
				}else{
					treeNode2=""+jso2+",";
				}
			}else{
				treeNode2="";
			}
			
		} 
		while (it3.hasNext()) { 
			Object[] objlist = (Object[]) it3.next();
			jso3=getColumnValue(objlist,viewArray);
			if(jso3!=null){
				
				if(treeNode3!=""){
					treeNode3+=jso3+",";
				}else{
					treeNode3=""+jso3+",";
				}
			}else{
				treeNode3="";
			}
			
		} 
		StringBuffer treeNodes=new StringBuffer();
		treeNodes.append("[");	
		if(!"".equals(treeNode)){
			treeNodes.append(treeNode.substring(0,treeNode.length()-1));
		}
		if(!"".equals(treeNode2)){
			treeNodes.append(",");
			treeNodes.append(treeNode2.substring(0,treeNode2.length()-1));
		}
		if(!"".equals(treeNode3)){
			treeNodes.append(",");
			treeNodes.append(treeNode3.substring(0,treeNode3.length()-1));
		}
		treeNodes.append("]");	
		return treeNodes.toString();
		
	}

	public void getOrganizationBFRTree2() throws Exception{
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/XML,charset=utf-8");
		response.setHeader("Charset", "utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/xml");
		PrintWriter out =  getResponse().getWriter();
		try {
			String returnTree = getOrganizationBFRTree();
			out.print("{\"ajaxResult\":"+returnTree+"}");
		} catch (Exception e) {
			e.printStackTrace();
			out.print("\"ajaxResult\":\"error\"}");
		}
	}
	
	/**
	 * 查询组织机构管理数据显示到jqrid
	 * @return OrganizationService
	 * @author 张海娜
	 * @date 2012-9-24 下午01:49:09
	 */
	public void queryOrganizationList() throws Exception{
		try {
			Map<String, String> filterMap = getPagerMap();
			//取出页面中的查询条件
			String orgName = getRequest().getParameter("orgName"); 
			String orgNo = getRequest().getParameter("orgNo");
			if(orgName != null && !"".equals(orgName)){
				orgName = StringUtil.encodingUrl(orgName);
				orgName = StringUtil.escapeString(orgName);
			}
			if(orgNo != null && !"".equals(orgNo)){
				orgNo = StringUtil.encodingUrl(orgNo);
				orgNo = StringUtil.escapeString(orgNo);
			}
			String flag = getRequest().getParameter("flag");
			String orgParentId = getRequest().getParameter("id");
			//将查询条件保存到Map里
			filterMap.put("orgName", orgName);
			filterMap.put("orgNo", orgNo);
			String[] viewArray = { "ORG_ID", "ORG_NO", "ORG_NAME",
					"ORG_DESC"};
			String returnStr = "";
			if("1".equals(flag)){
				// 查询所有的数据
				PageResult result = organizationService.queryOrganizationList(filterMap);
				 returnStr = getColumnJson(result, viewArray);
			}else if("2".equals(flag)){
				PageResult result = organizationService.findOrganizationByParentId(Integer.parseInt(orgParentId), filterMap);
				returnStr = getColumnJson(result, viewArray);
			}
			setContentType();
			PrintWriter out = getResponse().getWriter();
			System.out.println(returnStr);
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void searchUsersExec() throws Exception{
		try {
			Map<String, String> filterMap = getPagerMap();
			//取出页面中的查询条件
			//String flag = getRequest().getParameter("flag");
			String id = getRequest().getParameter("id");
			String userByOrganationid = getRequest().getParameter("userByOrganationid");
			//将查询条件保存到Map里
			String[] viewArray = {"userid","loginname","username","sexLabel:[{'1':'男','0':'女'}]","jobName","organization.orgName","activeLabel:[{'0':'外出试验','1':'有效'}]","lockFlagLabel:[{'0':'未锁定','1':'锁定'}]"};
			String returnStr = "";
			if(userByOrganationid != null){
				PageResult result = organizationService.queryuserByOrganationid(filterMap,userByOrganationid);
				returnStr = getColumnJson(result, viewArray);
			}else{
				if(id == null){
					// 查询所有的数据
					PageResult result = organizationService.queryUserList(filterMap);
					 returnStr = getColumnJson(result, viewArray);
				}else if(id != null){
					PageResult result = organizationService.findUserById(Integer.parseInt(id), filterMap);
					returnStr = getColumnJson(result, viewArray);
				}
			}

			setContentType();
			PrintWriter out = getResponse().getWriter();
			System.out.println(returnStr);
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/*
	 * 取得页面传过来的列表参数
	 */
	public Map getPagerMap(){
		if(page==null) page ="1";
		if(sidx==null) sidx ="id";
		if(rows==null) rows ="10";
		if(sord==null) sord ="asc";
		Map filterMap = new HashMap();//存储参数的map
		filterMap.put("page", Integer.parseInt(page));
		filterMap.put("rows", Integer.parseInt(rows));
		filterMap.put("sidx", sidx);
		filterMap.put("sord", sord);
		return filterMap;
	}

	/** 查询所有的组织结构的方法 */
//	public String searchAllOrgExec() throws IOException, ServiceException {
//		setContentType();
//		PrintWriter out = getResponse().getWriter();
//		List<Organization> orgList = organizationService.getAllTypes(null);//organizationService.findOrganizationByParentId(new Long(1));
//		String result = getOrgJson(orgList);
//		out.print(result);
//		System.out.println(result);
//		return null;
//	}
	/**
	 * 得到往页面传的josn对象
	 * String
	 * 2011-4-26下午09:06:10
	 * author：李数
	 */
	public String getColumnJson(PageResult result,String[] viewArray){
		int rowsInt=Integer.parseInt(rows);
		int totalRows = result.getRowCount(); //所有的行数
		int totalPages = (totalRows + rowsInt - 1) / rowsInt; //总页数
		List rowAll = result.getData();   //查询出的所有记录
		JSONObject obj = new JSONObject();
		obj.put("page", ""+page);
		obj.put("total",totalPages);
		obj.put("records",""+totalRows);
		JSONArray lineitemArray = new JSONArray(); 
		Iterator it = rowAll.iterator();
		while (it.hasNext()) { 
			Object[] objlist = (Object[]) it.next();
			lineitemArray.add(getColumnValue(objlist,viewArray));
		} 
		obj.put("rows", lineitemArray);
		return obj.toString();
	}
	public JSONObject getColumnValue(Object[] objlist,String[] viewArray) {
		JSONObject objlineitem = new JSONObject();	
        for (int i=0;i<viewArray.length;i++)
        { 
        	if(!StringUtil.isEmpty(viewArray[i])){
        		if(objlist[i] != null ){
        			if(viewArray[i].indexOf(":")>0){
            			String realfieldName = viewArray[i].substring(0,viewArray[i].indexOf(":"));
            			String jsonStr = viewArray[i].substring(viewArray[i].indexOf(":")+1);
    	        		JSONArray json = JSONArray.fromObject(jsonStr);
    	        		JSONObject job = json.getJSONObject(0);
    	        		if(job.containsKey(objlist[i].toString())){
    	        			 String realvalue = job.getString(objlist[i].toString());
    		        		 if(realvalue!=null){
    		        			 objlineitem.put(realfieldName, realvalue.toString());
    		        		 }
    	        		}else{
    	        			 objlineitem.put(realfieldName, objlist[i].toString());
    	        		}
            		}else{
            			 if(objlist[i]!=null){
            				 objlineitem.put(viewArray[i], objlist[i].toString());
            			 } else {
            				 objlineitem.put(viewArray[i], "");
            				}
            		}
	        	}else {
					 objlineitem.put(viewArray[i], "");
				}
        	}
        }
		return objlineitem;
	}
	public JSONObject getColumnValueRoot(Object[] objlist,String[] viewArray) {
		JSONObject objlineitem = new JSONObject();	
        for (int i=0;i<viewArray.length;i++)
        { 
        	if(!StringUtil.isEmpty(viewArray[i])){
        		if(objlist[i] != null ){
        			if(viewArray[i].indexOf(":")>0){
            			String realfieldName = viewArray[i].substring(0,viewArray[i].indexOf(":"));
            			String jsonStr = viewArray[i].substring(viewArray[i].indexOf(":")+1);
    	        		JSONArray json = JSONArray.fromObject(jsonStr);
    	        		JSONObject job = json.getJSONObject(0);
    	        		if(job.containsKey(objlist[i].toString())){
    	        			 String realvalue = job.getString(objlist[i].toString());
    		        		 if(realvalue!=null){
    		        			 objlineitem.put(realfieldName, realvalue.toString());
    		        			 objlineitem.put("isParent","true");
    		        		 }
    	        		}else{
    	        			 objlineitem.put(realfieldName, objlist[i].toString());
    	        			 objlineitem.put("isParent","true");
    	        		}
            		}else{
            			 if(objlist[i]!=null){
            				 objlineitem.put(viewArray[i], objlist[i].toString());
            				 objlineitem.put("isParent","true");
            			 } else {
            				 objlineitem.put(viewArray[i], "");
            				 objlineitem.put("isParent","true");
            				}
            		}
	        	}else {
					 objlineitem.put(viewArray[i], "");
				}
        	}
        }
		return objlineitem;
	}
	public JSONObject getColumnValueBranch(Object[] objlist,String[] viewArray) {
		JSONObject objlineitem = new JSONObject();	
        for (int i=0;i<viewArray.length;i++)
        { 
        	if(!StringUtil.isEmpty(viewArray[i])){
        		if(objlist[i] != null ){
        			if(viewArray[i].indexOf(":")>0){
            			String realfieldName = viewArray[i].substring(0,viewArray[i].indexOf(":"));
            			String jsonStr = viewArray[i].substring(viewArray[i].indexOf(":")+1);
    	        		JSONArray json = JSONArray.fromObject(jsonStr);
    	        		JSONObject job = json.getJSONObject(0);
    	        		if(job.containsKey(objlist[i].toString())){
    	        			 String realvalue = job.getString(objlist[i].toString());
    		        		 if(realvalue!=null){
    		        			 objlineitem.put(realfieldName, realvalue.toString());
    		        			 objlineitem.put("isParent","true");
    		        		 }
    	        		}else{
    	        			 objlineitem.put(realfieldName, objlist[i].toString());
    	        			 objlineitem.put("isParent","true");
    	        		}
            		}else{
            			 if(objlist[i]!=null){
            				 objlineitem.put(viewArray[i], objlist[i].toString());
            				 objlineitem.put("isParent","true");
            			 } else {
            				 objlineitem.put(viewArray[i], "");
            				}
            		}
	        	}else {
					 objlineitem.put(viewArray[i], "");
				}
        	}
        }
		return objlineitem;
	}
	/**
	 * 功能描述：组织机构树型结构添加类别
	 * @return
	 * @throws IOException
	 * @throws ServiceException String
	 * @author 张海娜
	 * @date 2012-9-24 下午03:23:15
	 */
	public String saveOrganizationExec() throws IOException, ServiceException{
		setContentType();
		try {
			String orgName = this.getRequest().getParameter("orgName");
			String orgNo = this.getRequest().getParameter("orgNo");
			String orgDesc = this.getRequest().getParameter("orgDesc");
			String orgOrder = this.getRequest().getParameter("orgOrder");
			String orgPrex = this.getRequest().getParameter("orgPrex");
			String departmentAs = this.getRequest().getParameter("departmentAs");
			Long orgParentId = Long.parseLong(this.getRequest().getParameter("orgParentId"));
			String orgParentIdsName = this.getRequest().getParameter("orgParentIdsName");
			
			//单位
			
			String unitAptitude = this.getRequest().getParameter("unitAptitude");
			String unitLevel = this.getRequest().getParameter("unitLevel");
			String unitAddr = this.getRequest().getParameter("unitAddr");
			String unitPostcode = this.getRequest().getParameter("unitPostcode");
			String unitStandard = this.getRequest().getParameter("unitStandard");
			String unitType = this.getRequest().getParameter("unitType");
		
			//判断试验型号名称是否重复
			Organization organization = new Organization();
			organization.setDelFlag("1");
			organization.setOrgId(orgParentId);
			organization.setOrgParentId(orgParentId);
			organization.setOrgNo(orgNo.toString().trim());
			organization.setOrgName(orgName.toString().trim());
			//organization.setDepartmentAs(departmentAs.toString().trim());
			//organization.setOrgDesc(orgDesc.toString().trim());
			
			organization.setUnitAddr(unitAddr);
			organization.setUnitAptitude(unitAptitude);
			organization.setUnitLevel(unitLevel);
			organization.setUnitPostcode(unitPostcode);
			organization.setUnitStandard(unitStandard);
			organization.setUnitType(unitType);
			
			
			if (orgOrder!=null&&!orgOrder.equals("")){
				organization.setOrgOrder(Long.parseLong(orgOrder));
			}
			if (orgPrex!=null&&!orgPrex.equals("")){
				organization.setOrgPrex(orgPrex);
			}
			PrintWriter out = getResponse().getWriter();
			JSONObject jsonObject = new JSONObject();
			Map filterMap = getPagerMap();
			PageResult result = organizationService.findOrganizationByDelflag(orgName.toString().trim(),filterMap,orgParentId);
			/*if(result.getRowCount()!=0 ){
				//getRequest().setAttribute("message", "机构名称已存在！");
				
				jsonObject.put("success",false);
				//jsonObject.put("result", getText("机构名称已存在！"));
				out.print("{\"ajaxResult\":\"have\"}");
				out.flush();
				out.close();
			}else*/{
				if((orgName.toString().trim()).equals(orgParentIdsName)){
					out.print("{\"ajaxResult\":\"haveparent\"}");
					out.flush();
					out.close();
				}else{
					organizationService.saveOrganization(organization);
					jsonObject.put("success",true);
					out.print("{\"ajaxResult\":\"success\"}");
					out.flush();
					out.close();
					logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理添加成功",1);
				}
				
			}
				
			return null;
		} catch (Exception e) {
			logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理添加失败",1);
			return null;
		}
	}
	/**
	 * 功能描述：组织机构树型结构修改类别
	 * @return
	 * @throws IOException
	 * @throws ServiceException String
	 * @author 张海娜
	 * @date 2012-9-24 下午04:16:07
	 */
	public String updateOrganizationExec() throws IOException, ServiceException{
		setContentType();
		Long orgId = Long.parseLong(this.getRequest().getParameter("orgId"));
		String orgName = this.getRequest().getParameter("orgName");
		String orgNo = this.getRequest().getParameter("orgNo");
		String orgDesc = this.getRequest().getParameter("orgDesc");
		String departmentAs = this.getRequest().getParameter("departmentAs");
		Long orgParentId = Long.parseLong(this.getRequest().getParameter("orgParentId"));
		String orgParentIdsName = this.getRequest().getParameter("orgParentIdsName");
		
		//单位
		
		String unitAptitude = this.getRequest().getParameter("unitAptitude");
		String unitLevel = this.getRequest().getParameter("unitLevel");
		String unitAddr = this.getRequest().getParameter("unitAddr");
		String unitPostcode = this.getRequest().getParameter("unitPostcode");
		String unitStandard = this.getRequest().getParameter("unitStandard");
		String unitType = this.getRequest().getParameter("unitType");
		
		Organization organization = new Organization();
		organization.setDelFlag("1");
		organization.setOrgId(orgId);
		organization.setOrgParentId(orgParentId);
		//organization.setOrgDesc(orgDesc.toString().trim());
		organization.setOrgName(orgName.toString().trim());
		//organization.setDepartmentAs(departmentAs.toString().trim());
		organization.setOrgNo(orgNo.toString().trim());

		organization.setUnitAddr(unitAddr);
		organization.setUnitAptitude(unitAptitude);
		organization.setUnitLevel(unitLevel);
		organization.setUnitPostcode(unitPostcode);
		organization.setUnitStandard(unitStandard);
		organization.setUnitType(unitType);
		
		PrintWriter out = getResponse().getWriter();
		
		JSONObject jsonObject = new JSONObject();
		List<Organization> organizations = organizationService.findByProperty(organization.getOrgName());
		Map filterMap = getPagerMap();
		PageResult result = organizationService.findOrganizationByDelflag(orgName.toString().trim(),filterMap,orgParentId);
		List list = result.getData();
		//!organizations.isEmpty() && !organizations.get(0).getOrgId().equals(organization.getOrgId())
		PageResult result1 = organizationService.findOrgByDelflag(orgId, orgName, filterMap);
		List list1 = result1.getData();
		if(!list.isEmpty()){
			Object[] obj = (Object[])list.get(0);
			System.out.println(obj[0].toString().equals(organization.getOrgId().toString())+"---------");
			if( !(obj[0].toString().equals(organization.getOrgId().toString()))){
				jsonObject.put("success",false);
				jsonObject.put("result", getText("机构名称已存在"));
				out.print("{\"result\":\"have\"}");
				out.flush();
				out.close();
			}else{
				if((orgName.toString().trim()).equals(orgParentIdsName)){
					out.print("{\"ajaxResult\":\"haveparent\"}");
					out.flush();
					out.close();
				}else{
					organizationService.updateOrganization(organization);
					jsonObject.put("success",true);
					out.print("{\"result\":\"success\"}");
					out.flush();
					out.close();
					logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理修改成功",1);
				}
				
				
			}
		}else if(!list1.isEmpty()){
			Object[] obj = (Object[])list1.get(0);
			System.out.println(obj[0].toString().equals(organization.getOrgId().toString())+"---------");
			if( !(obj[0].toString().equals(organization.getOrgId().toString()))){
				jsonObject.put("success",false);
				jsonObject.put("result", getText("机构名称已存在"));
				out.print("{\"result\":\"haveChild\"}");//父节点组织机构名称与该子节点的组织机构名称重复
				out.flush();
				out.close();
			}else{
				if((orgName.toString().trim()).equals(orgParentIdsName)){
					out.print("{\"ajaxResult\":\"haveparent\"}");
					out.flush();
					out.close();
				}else{
					organizationService.updateOrganization(organization);
					jsonObject.put("success",true);
					out.print("{\"result\":\"success\"}");
					out.flush();
					out.close();
					logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理修改成功",1);
				}
				
				
			}
		}else{
			if((orgName.toString().trim()).equals(orgParentIdsName)){
				out.print("{\"ajaxResult\":\"haveparent\"}");
				out.flush();
				out.close();
			}else{
				organizationService.updateOrganization(organization);
				jsonObject.put("success",true);
				out.print("{\"result\":\"success\"}");
				out.flush();
				out.close();
				logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理修改成功",1);
			}
		}
	  return null;
	}
	public String updateOrgExec() throws IOException, ServiceException{
		Long orgId = Long.parseLong(this.getRequest().getParameter("orgId"));
		String orgNo = this.getRequest().getParameter("orgNo");
		String orgName = this.getRequest().getParameter("orgName");
		String orgDesc = this.getRequest().getParameter("orgDesc");
		String departmentAs = this.getRequest().getParameter("departmentAs");
		String orgPrex = this.getRequest().getParameter("orgPrex");
		Long pId = Long.parseLong(this.getRequest().getParameter("pId"));
		String orgParentIdsName = this.getRequest().getParameter("orgParentIdsName");
		String orgOrder = this.getRequest().getParameter("orgOrder");
		Organization organization = new Organization();
		
		organization.setOrgParentId(pId);
		organization.setOrgId(orgId);
		organization.setDelFlag("1");
		organization.setOrgDesc(orgDesc.toString().trim());
		organization.setOrgNo(orgNo.toString().trim());
		organization.setOrgName(orgName.toString().trim());
		organization.setDepartmentAs(departmentAs.toString().trim());
		if (orgOrder!=null&&!orgOrder.equals("")){
			organization.setOrgOrder(Long.parseLong(orgOrder));
		}
		if (orgPrex!=null&&!orgPrex.equals("")){
			organization.setOrgPrex(orgPrex);
		}
		PrintWriter out = getResponse().getWriter();
		JSONObject jsonObject = new JSONObject();
		Map filterMap = getPagerMap();
		
		PageResult result = organizationService.findOrganizationByDelflag(orgName.toString().trim(),filterMap,pId);
		List list = result.getData();
		PageResult orgNoResult = organizationService.findOrganizationorgNoByDelflag(orgNo.toString().trim(),filterMap,pId);
		List orgNoList = orgNoResult.getData();
		PageResult result1 = organizationService.findOrgByDelflag(orgId, orgName, filterMap);
		List list1 = result1.getData();
		if(!list.isEmpty()){
			Object[] obj = (Object[])list.get(0);
			System.out.println(obj[0].toString().equals(organization.getOrgId().toString())+"---------");
			if( !(obj[0].toString().equals(organization.getOrgId().toString()))){
				//jsonObject.put("success",false);
				jsonObject.put("result", getText("机构名称已存在"));
				out.print("{\"ajaxResult\":\"have\"}");
			}
			else{
				if((orgName.toString().trim()).equals(orgParentIdsName)){
					out.print("{\"ajaxResult\":\"haveparent\"}");
					out.flush();
					out.close();
				}else{
					organizationService.updateOrganization(organization);
					logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理修改成功",1);
					out.print("{\"ajaxResult\":\"success\"}");
				}
				
			}
		}else if(!list1.isEmpty()){
			Object[] obj = (Object[])list1.get(0);
			System.out.println(obj[0].toString().equals(organization.getOrgId().toString())+"---------");
			if( !(obj[0].toString().equals(organization.getOrgId().toString()))){
				jsonObject.put("success",false);
				jsonObject.put("result", getText("机构名称已存在"));
				out.print("{\"result\":\"haveChild\"}");//父节点组织机构名称与该子节点的组织机构名称重复
				out.flush();
				out.close();
			}else{
				if((orgName.toString().trim()).equals(orgParentIdsName)){
					out.print("{\"ajaxResult\":\"haveparent\"}");
					out.flush();
					out.close();
				}else{
					organizationService.updateOrganization(organization);
					jsonObject.put("success",true);
					out.print("{\"result\":\"success\"}");
					out.flush();
					out.close();
					logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理修改成功",1);
				}
				
				
			}
		}else if(!orgNoList.isEmpty()){
			Object[] obj = (Object[])orgNoList.get(0);
			System.out.println(obj[0].toString().equals(organization.getOrgId().toString())+"---------");
			if( !(obj[0].toString().equals(organization.getOrgId().toString()))){
				jsonObject.put("success",false);
				jsonObject.put("result", getText("组织机构编号重复,请重新输入!"));
				out.print("{\"ajaxResult\":\"haveOrgNo\"}");
			}else{
				if((orgName.toString().trim()).equals(orgParentIdsName)){
					out.print("{\"ajaxResult\":\"haveparent\"}");
					out.flush();
					out.close();
				}else{
					organizationService.updateOrganization(organization);
					logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理修改成功",1);
					out.print("{\"ajaxResult\":\"success\"}");
				}
			}
		}else{
			if((orgName.toString().trim()).equals(orgParentIdsName)){
				out.print("{\"ajaxResult\":\"haveparent\"}");
				out.flush();
				out.close();
			}else{
				organizationService.updateOrganization(organization);
				logService.saveLogInfo(this.getLogBase(), "系统管理", "组织管理", "组织管理修改成功",1);
				out.print("{\"ajaxResult\":\"success\"}");
			}
		}
		out.flush();
		out.close();
		return null;
		
	}
	/**
	 * 列表删除功能
	 * @throws Exception void
	 * @author 张海娜
	 * @date 2012-9-24 下午04:38:51
	 */
	public void deleteOrganization() throws Exception{
	  	PrintWriter out = getResponse().getWriter();
	  	String delflag = getRequest().getParameter("delflag");
	  	try {
				String ids=getRequest().getParameter("ids");
				//Map<String, String> filterMap = getPagerMap();
				//PageResult count=organizationService.findUserByOrgId(ids, filterMap);
				 if(ids != null && !ids.isEmpty()){
					 if("2".equals(delflag)){
						// if(count.getRowCount() == 0){
						String userDelFlag = userService.findUserDelflagByOrgId(ids);
				 		if(!(userDelFlag.contains("1"))){
				 			organizationService.removeOrganization(ids);
				 			 out.print("{\"ajaxResult\":\"success\"}");
				 		}else{
							 out.print("{\"ajaxResult\":\"have\"}");
						}
						// organizationService.removeOrganization(ids);
					 }
				 }
				
			} catch (Exception e) {
				e.printStackTrace();
				out.print("{\"ajaxResult\":\"error\"}");
			}
	  }
	/**
	 * 查看
	 * @return String
	 * @author 张海娜
	 * @date 2012-9-24 下午05:33:01
	 */
	 public String searchOrganizationById(){
		 organization=organizationService.findOrganizationById(id);
			return SUCCESS;
			  
	 }
   /**
	 * 查询名称是否存在
	 * @throws Exception void
	 * @author 张海娜
	 * @date 2013-2-21 下午01:56:10
	 */
	public void getOrganizationNameExec() throws Exception{
		PrintWriter out = getResponse().getWriter();
		try{
			String orgName = StringUtil.encodingUrl(getRequest().getParameter("orgName"));
			String old = StringUtil.encodingUrl(getRequest().getParameter("old"));
			Organization organization = organizationService.findOrganizationName(orgName);
			if(orgName.equals(old)){
				out.print("true");
			}else{
				if(organization == null){
					out.print("true");
				}else{
					out.print("false");
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			out.print("false");
		}
	}
	/**
	 * 查询编号是否存在
	 * @throws Exception void
	 * @author 张海娜
	 * @date 2013-2-21 下午01:56:10
	 */
	public void findOrganizationByorgNoExec() throws IOException {
		PrintWriter out = getResponse().getWriter();
		try {	
			String orgNo = StringUtil.encodingUrl(getRequest().getParameter("orgNo"));
			String old = StringUtil.encodingUrl(getRequest().getParameter("old"));
			if(orgNo.equals(old)){
				out.print("{\"result\":\"success\"}");				
			}else{
				Organization organization = organizationService.findOrganizationByorgNo(orgNo);
				if (organization == null) {
						out.print("{\"result\":\"success\"}");
				} else {
					out.print("{\"result\":\"false\"}");
				}
			}			
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"false\"}");
		}
	}
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}

	public LogService getLogService() {
		return logService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}

	

	
	public String getOrgId() {
		return orgId;
	}

	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}

	public String getOrgName() {
		return orgName;
	}

	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}

	

	public int getOrgParentId() {
		return orgParentId;
	}

	public void setOrgParentId(int orgParentId) {
		this.orgParentId = orgParentId;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getRows() {
		return rows;
	}

	public void setRows(String rows) {
		this.rows = rows;
	}

	public String getSidx() {
		return sidx;
	}

	public void setSidx(String sidx) {
		this.sidx = sidx;
	}

	public String getSord() {
		return sord;
	}

	public void setSord(String sord) {
		this.sord = sord;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public OrganizationService getOrganizationService() {
		return organizationService;
	}
	
}
